package flow_type

import (
	"e-wallet/database"
	"errors"
	"sync"
)

var onceFlowType sync.Once

// 表字段同步
func init() {
	onceFlowType.Do(func() {
		err := database.Get().Sync2(&FlowType{})
		if err != nil {
			panic(err)
		}
	})
}

// 创建账户
func InsertOrUpdate(r *FlowType) error {
	engine := database.Get()
	has, err := engine.ID(r.Id).Exist(r)
	if err != nil {
		return err
	}
	if has {
		_, err = engine.ID(r.Id).Update(r)
	} else {
		_, err = engine.InsertOne(r)
	}
	return err
}

// 删除数据
func Delete(r *FlowType) error {
	engine := database.Get()
	_, err := engine.ID(r.Id).Delete(r)
	return err
}

// 查询所有
func FindAll() ([]FlowType, error) {
	engine := database.Get()
	var array []FlowType
	err := engine.Table(&FlowType{}).Find(&array)
	return array, err
}

// 查询单个
func Get(r *FlowType) (bool, error) {
	engine := database.Get()
	return engine.Get(r)
}

// 根据ID查询单个
func GetByID(id int64) (*FlowType, error) {
	r := &FlowType{}
	r.Id = id
	has, err := Get(r)
	if err != nil {
		return nil, err
	}
	if has {
		return r, nil
	}
	return nil, errors.New("not found")
}
